import HeaderView from "@/component/Header"
import TimeOut from "@/component/TimeOut"
import LeftSlider from "./component/LeftSlider"
import RightTab from "./component/RightTab"
import TabbarView from "@/component/Tabbar"
import { useEffect, useState } from "react"
import { GetCategory } from "@/api/category"

const Category = () => {
  const [flag, setFlag] = useState(false) // 错误提示   
  const [leftCollapse, setLeftCollapse] = useState<any>([]) // 左侧slideBar
  const [menuID, setMenuID] = useState(0) // 左侧slider对应的ID

  // 数据初始化
  const init = async () => {
    const res = await GetCategory().catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setFlag(true)
    })
    try {
      if(res?.status === 200) {
        setLeftCollapse(res.data.categories)
      }
    } catch (error) {
      console.log(error)  
    }
  }

  // 左侧sliderBar点击 获得对应ID
  const sliderIDClick = (id: number) => {
    setMenuID(id)
  }

  useEffect(() => { init() }, [])

  return (
    <>
      {/* 头部信息 */}
      <HeaderView title="商品分类" backIcon={false}/>

      {
        leftCollapse.length !== 0
        &&
        <>
         {/* 左侧slideBar */}
         <LeftSlider leftCollapse={leftCollapse} sliderIDClick={sliderIDClick}/>

         {/* 右侧tabbar和List */}
         <RightTab menuID={menuID}/>
        
         {/* tabbar信息 */}
         <TabbarView/>
        </>
      }

      {/* 错误提示页面 */}
      {flag && <TimeOut/>}
    </>
  ) 
}

export default Category